<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/29 0029
 * Time: 下午 22:00
 */
namespace app\admin\behavior;
use think\Session;
use traits\controller\Jump;

/**
 * 权限验证行为
 * Class CheckAuth
 * @package app\admin\behavior
 */
class CheckAuth {
    protected $request;
    use Jump;
    /**
     * 监听module_init
     * @param $request    request对象
     */
    public function run(&$request){

        $this->module = $request->module();
        $this->controller = $request->controller();
        $this->action = $request->action();
        $this->param = $request->param();

        if ($this->controller === 'Service'){
            return;
        }
        if (strpos($this->controller,'Get.')===0){
            return;
        }
        if (!$this->checkAuth()){
            $this->redirect('admin/service/login');
        }
        if (!$this->checkAccess()){
            $this->error('没有权限');
        }
    }

    /**
     * 权限校验
     * @return bool
     */
    private function checkAccess(){
        $admin_id = Session::get('admin_id');
        if ((int)$admin_id === 1){
            return true;
        }

        $rule = "$this->module/$this->controller/$this->action";
        $access = db('auth_access')->where(['rule'=>$rule,'status'=>0])->field('id,rule,param')->find();
        if (empty($access)){
            return false;
        }
        if (empty($access['param'])){
            return true;
        }

        parse_str($access['param'],$param_arr);
        foreach ($param_arr as $key =>$value){
            if (!isset($this->param[$key]) || $this->param[$key] !== $value){
                return false;
            }
        }
        return true;
    }

    /**
     * 登录判断
     * @return bool
     */
    private function checkAuth(){
        return Session::has('admin_id');
    }
}